package top.lishuoboy.hibernate.validator.dto;

import cn.hutool.core.exceptions.ExceptionUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;

import java.io.Serializable;

/**
 * <h1>结果</h1>
 * <p>
 * 2024-10-25
 *
 * @author lishuoboy
 */
@ApiModel(description = "结果")
@Getter
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    //    /** 响应码。不要响应码，省了每次费脑子 */
//    @ApiModelProperty(value = "状态（0：成功）", position = 1)
//    private Integer code;

    @ApiModelProperty(value = "消息（success为成功，否则失败详情）", position = 20)
    private String msg;

    @ApiModelProperty(value = "数据", position = 30)
    private T data;

    /** 私有化构造器 */
    private Result(String msg, T data) {
        this.msg = msg;
        this.data = data;
    }

    /** 成功 */
    public static <T> Result<T> success(T t) {
        return new Result<>(ResultEnum.success.name(), t);
    }

    /** 成功 */
    public static <T> Result<T> success() {
        return success(null);
    }

    /** 失败 */
    public static <T> Result<T> failure(String msg, T data) {
        return new Result<>(msg, data);
    }

    /** 失败 */
    public static <T> Result<T> failure(ResultEnum msg, T data) {
        return failure(msg.getMsg(), data);
    }

    /** 失败 */
    public static Result<Object> failure(ResultEnum msg) {
        return failure(msg.getMsg(), null);
    }

    /** 失败 */
    public static Result<String> failure(Throwable t) {
        return failure(ResultEnum.serverError.getMsg(), ExceptionUtil.getRootCauseMessage(t));
    }
}
